package com.codeyourlife.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.codeyourlife.dao.SearchDao;
import com.codeyourlife.entity.Course;

@Repository("searchDao")
public class SearchDaoImpl implements SearchDao {

	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Object> getCourseBySearchContent(String searchContent,int pageNumber) {
		System.out.println("====searchdao====");
		
		List<Course> courseList = new ArrayList<Course>();
		List<Course> queryCourseByCondition = new ArrayList<Course>();
		int fixNumber = 3;
		try {
			Session session=this.getSessionFactory().getCurrentSession();
			Query query = this.getSessionFactory().getCurrentSession().createQuery(
					"from Course c where (c.coursename LIKE '%"+searchContent+"%' OR c.brief LIKE '%"+searchContent+
					"%' OR c.detail LIKE '%"+searchContent+"%')");
			queryCourseByCondition = query.list();
			session.close();
			System.out.println("the length of queryCourseByCondition = " + queryCourseByCondition.size());
			
			int totalNumber = queryCourseByCondition.size() / fixNumber;
			if (queryCourseByCondition.size() % fixNumber != 0) {
				/*firstCourse.setClick_nums(totalNumber);*/
				totalNumber = totalNumber + 1;
			}
			
			for (int i = (pageNumber - 1) * fixNumber; i < pageNumber * fixNumber; i++) {
				if (i == queryCourseByCondition.size()) {
					break;
				}
				courseList.add(queryCourseByCondition.get(i));
			}
			
			ArrayList<Object> arr = new ArrayList();
			System.out.println(totalNumber);
			arr.add("{rtotalPage:" + totalNumber + "}");
			arr.addAll(courseList);
			return arr;
		} catch (Exception e) {
			System.out.println("Dao==findCourseByEle: " + e.getStackTrace());
		}
		return null;
	}
}
